package com.example.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.reggie.common.R;
import com.example.reggie.dto.DishDto;
import com.example.reggie.dto.SetmealDto;
import com.example.reggie.entity.*;
import com.example.reggie.service.CategoryService;
import com.example.reggie.service.SetmealDishService;
import com.example.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SetmealDishService setmealDishService;
//    @Autowired
//    private RedisTemplate redisTemplate;


    /**
     * 新增套餐信息同时保存套餐菜品数据
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache",key = "#setmealDto.categoryId")
    public R<String> save(@RequestBody SetmealDto setmealDto) {
        log.info(setmealDto.toString());
        setmealService.saveWithDish(setmealDto);
//        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
//        for(SetmealDish setmealDish:setmealDishes){
//            setmealDishService.save(setmealDish);
//        }

//        //清理redis缓存
//        String key="setmeal_"+setmealDto.getCategoryId()+"_1";
//        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    /**
     * 分页展示套餐信息
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){

        //构造分页构造器对象
        Page<Setmeal> pageInfo=new Page<>(page,pageSize);
        Page<SetmealDto> setmealDtoPage=new Page<>();

        //条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper=new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(name!=null,Setmeal::getName,name);
        //添加排序条件
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        //执行分页查询
        setmealService.page(pageInfo,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageInfo,setmealDtoPage,"records");

        List<Setmeal> records=pageInfo.getRecords();
        List<SetmealDto> list=new ArrayList<>();

        for (Setmeal setmeal:records){
            SetmealDto setmealDto=new SetmealDto();

            Long categoryId=setmeal.getCategoryId();//分类ID
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category!=null){
                String categoryName=category.getName();
                setmealDto.setCategoryName(categoryName);
            }

            //对象拷贝
            BeanUtils.copyProperties(setmeal,setmealDto);

            list.add(setmealDto);
        }

        setmealDtoPage.setRecords(list);
        return R.success(setmealDtoPage);
    }

    /**
     * 根据id删除套餐信息
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> delete(Long ids){
        setmealService.delete(ids);

        return R.success("套餐删除成功");
    }

    /**
     * 根据id数组和path变量更新套餐状态信息
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> updateStatus(@PathVariable Integer status,Long[] ids){
        log.info(status+"     "+ids.toString());

        for(Long id:ids){
            LambdaUpdateWrapper<Setmeal> updateWrapper =new LambdaUpdateWrapper<>();
            updateWrapper.set(Setmeal::getStatus,status).eq(Setmeal::getId,id);
            setmealService.update(updateWrapper);
//            Setmeal setmeal = setmealService.getById(id);
//            String key="setmeal_"+setmeal.getCategoryId()+"_1";
//            redisTemplate.delete(key);
        }


        return R.success("套餐状态信息修改成功");
    }

    /**
     * 显示所有的套餐信息
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId")
    public R<List<SetmealDto>> list(Setmeal setmeal){

        List<SetmealDto> dtoList=null;
//        String key="setmeal_"+setmeal.getCategoryId()+"_"+setmeal.getStatus();

//        //先从redis中获取缓存数据
//        dtoList= (List<SetmealDto>) redisTemplate.opsForValue().get(key);
//
//        if(dtoList!=null){
//            //如果存在，则直接放回，无需查询数据库
//            return R.success(dtoList);
//        }

        //如果不存在，需要查询数据库，将查询到的数据缓存到redis
        //构造查询条件
        LambdaQueryWrapper<Setmeal> queryWrapper=new LambdaQueryWrapper();
        //添加查询条件
        queryWrapper.eq(setmeal.getCategoryId()!=null,Setmeal::getCategoryId,setmeal.getCategoryId());
        queryWrapper.eq(Setmeal::getStatus,1);
        //添加排序条件
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        //查询出套餐数据
        List<Setmeal> list=setmealService.list(queryWrapper);
        dtoList=new ArrayList<>();

        for(Setmeal s:list){
            SetmealDto SD=new SetmealDto();
            BeanUtils.copyProperties(s,SD);
            dtoList.add(SD);
        }

        for(SetmealDto setmealDto:dtoList){
            //设置套餐的菜品数据
            LambdaQueryWrapper<SetmealDish> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(SetmealDish::getSetmealId,setmealDto.getId());
            setmealDto.setSetmealDishes(setmealDishService.list(wrapper));
            //根据ID查询分类对象
            Category category = categoryService.getById(setmealDto.getCategoryId());
            setmealDto.setCategoryName(category.getName());
        }
//        //将查询到的数据缓存到redis
//        redisTemplate.opsForValue().set(key,dtoList,60, TimeUnit.MINUTES);

        return R.success(dtoList);
    }

    /**
     * 根据套餐id给出信息
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public R<SetmealDto> getSetmeal(@PathVariable Long id){
        Setmeal setmeal = setmealService.getById(id);
        SetmealDto dto=new SetmealDto();
        BeanUtils.copyProperties(setmeal,dto);
        //设置分类的名字
        String CategoryName = categoryService.getById(dto.getCategoryId()).getName();
        dto.setCategoryName(CategoryName);
        //获取套餐菜品信息列表
        LambdaQueryWrapper<SetmealDish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,setmeal.getId());
        List<SetmealDish> setmealDishes = setmealDishService.list(queryWrapper);
        //设置套餐菜品列表
        dto.setSetmealDishes(setmealDishes);

        return R.success(dto);
    }

    /**
     * 更新套餐信息
     * @param setmealDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "setmealCache",key = "#setmealDto.categoryId")
    public R<String> update(@RequestBody SetmealDto setmealDto){
        setmealService.updateById(setmealDto);
        //先把套餐菜品信息移除
        LambdaQueryWrapper<SetmealDish> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId,setmealDto.getId());
        setmealDishService.remove(queryWrapper);
        //保存新的套餐菜品信息
        for (SetmealDish setmealDish:setmealDto.getSetmealDishes()
        ) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        setmealDishService.saveBatch(setmealDto.getSetmealDishes());

        return R.success("套餐信息更新成功");
    }
}
